package com.hbter630.change.controller.api;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbter630.change.DTO.CategoryDTO;
import com.hbter630.change.entity.Cartproduct;
import com.hbter630.change.entity.Category;
import com.hbter630.change.entity.Product;
import com.hbter630.change.service.CartproductService;
import com.hbter630.change.service.CategoryService;
import com.hbter630.change.service.ProductService;
import com.hbter630.change.utils.ProductRedis;
import com.hbter630.change.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * @Title: ApiHomeController
 * @Author 笑霸fianl
 * @Package com.hbter630.change.controller.api
 * @Date 2023/5/27 14:47
 * @描述:
 */

@RestController
@RequestMapping("/api")
@Api(tags = "3.首页三级分类")
@Slf4j
public class ApiHomeController {

    @Autowired
    private CategoryService categoryService;

    //商品
    @Autowired
    private ProductService productService;

    //购物车
    @Autowired
    private CartproductService cartproductService;

    @Resource
    private RedisTemplate redisTemplate;

    @ApiOperation(notes = "获取首页商品分类",value = " 获取首页商品分类",
            httpMethod = "GET", response = Result.class)
    @GetMapping("/product/getBaseCategoryList")
    public Result getBaseCategoryLis(){

        List<Category> list = categoryService.list();

        return Result.ok().addData(list);
    }


    @ApiOperation(notes = "获取商品",value = "获取商品",
            httpMethod = "POST", response = Result.class)
    @PostMapping("/list")
    public Result getList(@RequestBody  CategoryDTO categoryDTO){



        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.eq("name", categoryDTO.getCategoryName());
        Category one = categoryService.getOne(categoryQueryWrapper);
        //根据id找商品
        Integer categoryId = one.getCategoryId();


        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id",categoryId);
        List<Product> list = productService.list(wrapper);


        return Result.ok().addData(list);
    }


    /**
     * item
     */
    @GetMapping("/item/{id}")
    public Result item(@PathVariable("id") long id){
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("Product_id",id);
        Product one = productService.getOne(productQueryWrapper);
        return Result.ok().addData(one);
    }


    /**
     * 添加购物车
     * @param id
     * @param count
     * @return
     */
    @PostMapping("/cart/addToCart/{id}/{count}")
    public Result addToCart(@PathVariable("id") Integer id,
                            @PathVariable("count") Integer count

    ){
        Object loginId = StpUtil.getLoginId();//用户id
        log.info("添加刀购物车===当前用户id：{}",loginId);
        Cartproduct cartproduct = new Cartproduct();
        cartproduct.setQuantity(count);
        cartproduct.setProductId(id);
        Product byId = productService.getById(id);
        cartproduct.setPrice(byId.getPrice());//设置单价
        int i = Integer.parseInt(loginId.toString());
        cartproduct.setUserId(i);
        cartproductService.save(cartproduct);
        return Result.ok().addData(Result.ok());
    }

    /**
     * 查询所有商品
     */
    @ApiOperation(notes = "查询所有商品",value = "查询所有商品",
            httpMethod = "GET", response = Result.class)
    @GetMapping("/alllist")

    public Result alllist(){
        //先获取redis中的数据
        Object ob =redisTemplate.opsForValue().get(ProductRedis.Product_list_key);
        if(ob != null && BeanUtil.isNotEmpty(ob)){
            List<Product> products = JSONUtil.toList((String) ob, Product.class);
            return Result.ok().addData(products);
        }
        log.info("\n=======列表商品没有缓存========\n");

        List<Product> list = productService.list();
        int size = list.size();
        Collections.shuffle(list);//打乱数据
        int l =size/4;

        log.info("获取商品的数量--------{}",size);
        ArrayList<Product> products = new ArrayList<>();
        for (int i=0;i<l*4;i++){
            products.add(list.get(i));
        }

        // 获取前l*4个元素（即随机的l*4个元素）
        List<Product> randomElements = list.subList(0, l*4);


        String jsonStr = JSONUtil.toJsonStr(randomElements);
        redisTemplate.opsForValue().set(ProductRedis.Product_list_key,jsonStr);
        return Result.ok().addData(randomElements);
    }

    /**
     * 分页查询所有商品
     */
    @ApiOperation(notes = "分页查询所有商品",value = "分页查询所有商品",
            httpMethod = "GET", response = Result.class)
    @GetMapping("/alllistByPage/{current}/{limit}")
    public Result alllistByPage(@PathVariable("current") long current,
                                @PathVariable("limit") long limit){

        return productService.alllistByPage(current,limit);
    }

    /**
     * 根据删除商品
     */
    @ApiOperation(notes = "根据删除商品",value = "根据删除商品",
            httpMethod = "DELETE", response = Result.class)

    @DeleteMapping("handleDelete/{id}")
    public Result handleDelete(@PathVariable("id") Integer id){
        boolean b = productService.removeById(id);
        redisTemplate.delete(ProductRedis.Product_list_key);
        return Result.ok();
    }
    /**
     * 根据id获取商品详细
     */
    @ApiOperation(notes = "根据id获取商品详细",value = "根据id获取商品详细",
            httpMethod = "GET", response = Result.class)
    @GetMapping("getProductById/{id}")
    public Result getProductById(@PathVariable("id") Integer id){
        Product byId = productService.getById(id);
        return Result.ok().addData(byId);
    }

    /**
     * 添加（保存）新的商品
     */
    @ApiOperation(notes = "添加（保存）新的商品",value = "添加（保存）新的商品",
            httpMethod = "POST", response = Result.class)
    @PostMapping("updateNew")
    public Result updateNew(@RequestBody Product product){
        log.info("\n================getProductById\n");
        redisTemplate.delete(ProductRedis.Product_list_key);
        productService.updateNew(product);
        return Result.ok();
    }


}
